import { action, autorun, computed, makeAutoObservable, makeObservable, observable } from "mobx";

export type TodoItemType = {
  task: string;
  completed: boolean;
  assignee: null | { name: string };
};

export class ObservableTodoStore {
  todos: TodoItemType[] = [];
  pendingRequests = 0;

  constructor() {
    // MARK: 可以使用 makeAutoObservable(this) 简化这个过程
    makeAutoObservable(this);
    /* makeObservable(this, {
      todos: observable,
      pendingRequests: observable,
      // 派生属性
      completedTodosCount: computed,
      report: computed,
      // 方法
      addTodo: action,
    });
    autorun(() => console.log(this.report)); */
  }

  get completedTodosCount() {
    return this.todos.filter(
      todo => todo.completed === true
    ).length;
  }

  get report() {
    if (this.todos.length === 0)
      return "<none>";
    const nextTodo = this.todos.find(todo => todo.completed === false);
    return `Next todo: "${nextTodo ? nextTodo.task : "<none>"}". ` +
      `Progress: ${this.completedTodosCount}/${this.todos.length}`;
  }

  addTodo(task: string) {
    this.todos.push({
      task: task,
      completed: false,
      assignee: null
    });
  }
}

const observableTodoStore = new ObservableTodoStore();

export default observableTodoStore;